package william.tree;

/**
 * @author ZhangShenao
 * @date 2024/1/16
 * @description <a href="https://leetcode.cn/problems/invert-binary-tree/description/">...</a>
 */
public class Leetcode226_翻转二叉树 {
    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    /**
     * 采用递归算法
     * 针对当前节点,依次递归地将左、右子树进行翻转,然后将左、右子节点进行交换
     * <p>
     * 时间复杂度O(N) 需要遍历树一次
     * 空间复杂度O(logN) 递归栈深度=树高度
     */
    public TreeNode invertTree(TreeNode root) {
        //递归终止条件
        if (root == null){
            return root;
        }

        //调用递归实现,依次将左、右子树进行交换
        invertTree(root.left);
        invertTree(root.right);

        //将左、右子节点进行交换
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;

        //返回翻转后的根节点
        return root;
    }
}
